package com.ghj.utils.httpclient;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class GetRequest {
    private String url;
    private CloseableHttpClient client;
    private boolean firstParam = true;

    public GetRequest(String apiUrl) throws IOException {
        client = HttpClients.createDefault();
        this.url = apiUrl;
    }

    public GetRequest param(String key, String value) throws UnsupportedEncodingException {
        if (firstParam) {
            url += String.format("?%s=%s", key, URLEncoder.encode(value, "UTF-8"));
            firstParam = false;
        }
        url += String.format("&%s=%s", key, URLEncoder.encode(value, "UTF-8"));
        return this;
    }

    public void execute(Callback cb) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            Map map = new ObjectMapper().readValue(reader.readLine(), Map.class);
            cb.call(map);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    public void depose() throws IOException {
        client.close();
    }
}